<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
/**
 * 售后管理
 *
 * @icon fa fa-circle-o
 */
class OrderRefund extends Backend
{

    /**
     * OrderRefund模型对象
     * @var \app\admin\model\deerhome\OrderRefund
     */
    protected $model = null;

    protected $relationSearch = true; 

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\OrderRefund;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->with(["user"])
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
       
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if(!isset($params['status'])){
            $this->error("请选择审核结果状态");
        }
        if(!\in_array($params['status'],[2,3])){
            $this->error("请选择审核结果状态");
        }
        if(\bccomp($row['price'],$params['price_refund'],2) === -1){
            $this->error("退款金额不能超过订单金额");
        }
        $params['ac_admin']=$this->auth->username;
        $params['ac_admin_time']=\date("Y-m-d H:i:s");
        $order=Db::name("deerhome_order")->where("sn",$row['order_sn'])->find();
        if(!$order){
            $this->error("订单不存在");
        }
        if($order['worker_price_to_wallet']==1 && $params['status'] == 2){
            $this->error("该订单已经结算到服务人员钱包，无法退款");
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            $acLog="";
            //拒绝则退回订单状态
            if($params['status'] == 3){
                Db::name("deerhome_order")->where("id",$order['id'])->update(['status'=>$row['order_old_status']]);
                $acLog="拒绝退款,原因{$params['ac_admin_note']}。";
            }
            //通过则提交给支付平台退款
            if($params['status'] == 2){
                $this->weixinRefund($order,$row,$params['price_refund']);
                Db::name("deerhome_order")->where("id",$order['id'])->update(['worker_price'=>0,'worker_price_note'=>'用户退款','status'=>7,'time_done'=>\date("Y-m-d H:i:s")]);
                $acLog="已退款,金额￥{$params['price_refund']}。";
            }
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'管理员:'.$params['ac_admin'],
                'note'=>$acLog
            ]);
            Db::commit();
        } catch (ValidateException|PDOException|\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        //订单取消通知师傅
        try{
            if($params['status'] == 2 && $order['order_type']==1 && $order['worker_id']>0){
                \Tools\Msg::toWorkerCancelOrder($order['worker_id'],$order['sn']);
            }
        }catch(\Exception $e){
            \think\Log::error("订单取消通知师傅失败：".$e->getMessage()."\n".json_encode($row,JSON_UNESCAPED_UNICODE));
        }
        $this->success();
    }

    //退款
    protected function weixinRefund($orderData,$refundRowData,$refundPrice){
        $config=$this->getWeixinConfig();
        $Refund = null;
        //计算多次支付的金额，和要退款的金额
        $order=Db::name("deerhome_order_pay_log")->where("order_sn",$orderData['sn'])->where("status",2)->where("payway_type",1)->select();
        if(count($order)==0){
            throw new \Exception("该订单未支付");
        }
        $hasWePay=false;
        foreach ($order as $key => $value) {
            if($value['pay_way']=="微信支付"){
                $hasWePay=true;
                break;
            }
        }
        if($hasWePay){
            $Refund = \WePayV3\Order::instance($config);
        }
        $refundPrice=$refundPrice*100;
        $refundLeft=$refundPrice;
        foreach ($order as $key => $value) {
            $out_trade_no=$value['order_sn']."S".$value['id'];
            $out_refund_no=$out_trade_no."T".$refundRowData['id']."-".$key;
            $totalPrice=$value['price']*100;
            //已经全部退完了
            if($totalPrice>=$refundLeft){
                $refundPriceRow=$refundLeft;
                if($value['pay_way']=="储值卡支付"){
                    $this->toUserWallet($value['order_sn'],$value['deerhome_user_id'],$refundPriceRow);
                }
                if($value['pay_way']=="微信支付"){
                    $Refund->createRefund([
                        "out_trade_no"=>$out_trade_no,
                        "out_refund_no"=>$out_refund_no,
                        'amount'       => ['total'=>$totalPrice,'refund' => $refundPriceRow, 'currency' => 'CNY'],
                    ]);
                    $this->toUserWechat($value['order_sn'],$value['deerhome_user_id'],$refundPriceRow);
                }
                break;
            }
            //循环退款
            $refundPriceRow=$totalPrice;
            $refundLeft=$refundLeft-$totalPrice;
            if($value['pay_way']=="储值卡支付"){
                $this->toUserWallet($value['order_sn'],$value['deerhome_user_id'],$refundPriceRow);
            }
            if($value['pay_way']=="微信支付"){
                $Refund->createRefund([
                    "out_trade_no"=>$out_trade_no,
                    "out_refund_no"=>$out_refund_no,
                    'amount'       => ['total'=>$totalPrice,'refund' => $refundPriceRow, 'currency' => 'CNY'],
                ]);
                $this->toUserWechat($value['order_sn'],$value['deerhome_user_id'],$refundPriceRow);
            }
        }
    }

    //微信配置
    protected function getWeixinConfig(){
        $arr=[];
        $arr['appid']=config("site_deerhome.wechat_app_id");
        $arr['appsecret']=config("site_deerhome.wechat_app_secret");
        $arr['mch_id']=config("site_deerhome.wechat_app_mch_id");
        $arr['mch_v3_key']=config("site_deerhome.wechat_app_mch_v3_key");
        $arr['cert_public']=ROOT_PATH . 'public' . DS . config("site_deerhome.wechat_app_mch_cert");
        $arr['cert_private']=ROOT_PATH . 'public' . DS . config("site_deerhome.wechat_app_mch_key");
        return $arr;
    }
    //退款：：储值卡
    protected function toUserWallet($sn,$user_id,$price){
        $price=$price<0?$price*-1:$price;
        $price=$price/100;
        $log=[
            'deerhome_user_id'=>$user_id,
            'is_wallet'=>1,
            'status'=>2,
            'price'=>$price,
            'order_sn'=>$sn,
            'payway_type'=>1,
            'pay_way'=>"储值卡支付",
            'pay_time'=>\date("Y-m-d H:i:s"),
            'add_time'=>\date("Y-m-d H:i:s"),
            'note'=>'退款到储值卡，订单'.$sn,
        ];
        Db::name("deerhome_order_pay_log")->insert($log);
        Db::name("deerhome_user")->where("id",$user_id)->update([
            "wallet_charge"=>Db::raw("wallet_charge+{$price}")
        ]);
    }
    //退款：：微信支付
    protected function toUserWechat($sn,$user_id,$price){
        $price=$price/100*-1;
        $log=[
            'deerhome_user_id'=>$user_id,
            'status'=>2,
            'price'=>$price,
            'order_sn'=>$sn,
            'payway_type'=>1,
            'pay_way'=>"微信支付",
            'pay_time'=>\date("Y-m-d H:i:s"),
            'add_time'=>\date("Y-m-d H:i:s"),
            'note'=>'原路退回款项，订单'.$sn,
        ];
        Db::name("deerhome_order_pay_log")->insert($log);
    }
}
